<?php

/**
 * system function
 *
 * @author haifeng.wu
 */

/**
 * 取消系统的魔术引号
 *
 * @param array $array
 * @return void
 */
function cancelMagicQuotes(&$array)
{
    if (get_magic_quotes_gpc()) {
        foreach ($array as $key=>$value) {
            if (is_array($array[$key])) {
                cancelMagicQuotes($array[$key]);
            } else if (is_string($array[$key])) {
                $array[$key] = stripslashes($value);
            }
        }
    }
}

/**
 * 数组stripslashes
 *
 * @param array $data
 * @return array
 */
function stripslashesArray($data)
{
    $array=array();
    $field = array();
    while ($field = each($data)) {
        $array[$field['key']] = stripslashes($field['value']);
    }
    return $array;
}

/**
 * 数组addslashesArray
 *
 * @param array $data
 * @return array
 */
function addslashesArray($data)
{
    $array=array();
    while ($field = each($data)) {
        $array[$field['key']] = addslashes($field['value']);
    }
    return $array;
}

/**
 * 输出函数
 *
 * @param string $string
 * @param string $emptyString
 * @param integer $isReplaceLine
 * @return string
 */
function noEmptyEcho($string, $emptyString="--", $isReplaceLine=0)
{
    if (empty($string)) {
        return $emptyString;
    }else{
        if ($isReplaceLine==1) {
            $val=str_replace("\r", "", $val);
            $val=str_replace("\n", "<br>", $val);
        }
        return $val;
    }
}

/**
 * 替换数据库中的换行
 *
 * @param string $string
 * @return string
 */
function replaceBreak($string)
{
	$string = str_replace("\r\n", '<br />', $string);
	$string = str_replace("\n", '<br />', $string);
	$string = str_replace("\r", '<br />', $string);
	return $string;
}

/**
 * 替换数据库中的换行
 *
 * @param string $string
 * @return string
 */
function stripTags($string, $allowableTags = '')
{
	$string = str_replace(array('&nbsp;', ), '<br />', $string);
	$string = preg_replace("/&[\w]{1,20};/", ' ', $string);
	$string = strip_tags($string, $allowableTags);
	return $string;
}

/**
 * 计算utf8的字节长度(一中文字占2个字节)
 *
 * @param string $string
 * @return integer
 */
function strlenUtf8($string)
{
    $count = 0;
    for ($i = 0; $i < strlen($string); $i++) {
        $value = ord($string[$i]);
        if ($value > 127) {
            $count++;
            if ($value >= 192 && $value <= 223) $i++;
            else if ($value >= 224 && $value <= 239) $i = $i + 2;
            else if ($value >= 240 && $value <= 247) $i = $i + 3;
            else die('Not a UTF-8 compatible string');
        }
        $count++;
    }
    return $count;
}

/**
 * utf8截取字符(一中文字占2个字节)
 *
 * @param string $string
 * @param integer $position
 * @param integer $length
 * @return string
 */
function substrUtf8($string, $position, $length)
{
    $startPosition = strlen($string);
    $startByte = 0;
    $endPosition = strlen($string);
    $count = 0;
    for ($i = 0; $i < strlen($string); $i++) {
        if ($count >= $position && $startPosition > $i) {
            $startPosition = $i;
            $startByte = $count;
        }
        if (($count-$startByte) >= $length) {
            $endPosition = $i;
            break;
        }    
        $value = ord($string[$i]);
        if ($value > 127) {
            $count++;
            if ($value >= 192 && $value <= 223) $i++;
            else if ($value >= 224 && $value <= 239) $i = $i + 2;
            else if ($value >= 240 && $value <= 247) $i = $i + 3;
            else die('Not a UTF-8 compatible string');
        }
        $count++;

    }
    return(substr($string, $startPosition, $endPosition-$startPosition));
}

/**
 * utf8截取字符(中文), 多余的省略
 *
 * @param string $data
 * @param integer $length
 * @param string $moreText
 * @return string
 */
function substrMoreCn($data, $length, $moreText="...")
{
    if ( $length>0 ) {
        $dataTemp = strip_tags($data);
        if (strlenUtf8($dataTemp)-strlenUtf8($moreText) > $length && strlenUtf8($dataTemp) > strlenUtf8($moreText)) {
            $dataTemp = substrUtf8($dataTemp, 0, $length-strlenUtf8($moreText) ) . $moreText;
        } else {
            $dataTemp = $data;
        }
    } else {
        $dataTemp = $data;
    }
    return $dataTemp;
}

/**
 * utf8截取字符(英文), 多余的省略
 *
 * @param string $data
 * @param integer $length
 * @param string $moreText
 * @return string
 */
function substrMoreEn($data, $length, $moreText="...")
{
    if ($length > 0) {
        $dataTemp = strip_tags($data);
        $dataTemp = trim($dataTemp);
        if (strlen($dataTemp)-strlen($moreText) > $length && strlen($dataTemp) > strlen($moreText)) {
            $length=$length-strlen($moreText);
            if (substr($dataTemp, 0, $length+1 ) == ' ') {
                $dataTemp=substr($dataTemp, 0, $length) . $moreText;
            } else {
                for ( $i = $length-1; $i >=0 ; $i--) {
                    if ( substr($dataTemp, $i, 1) == ' ' ) {
                        $dataTemp = substr($dataTemp, 0,  $i) . $moreText;
                        break;
                    }
                }
            }
        } else {
            $dataTemp = $data;
        }
    } else {
        $dataTemp = $data;
    }
    return $dataTemp;
}

/**
 * 时间转字符
 *
 * @param integer $time
 * @return string
 */
function timeToString($time)
{
    $day = floor($time/(24*3600));
    $daySurplusTime = $time-$day*24*3600;
    $hour = floor($daySurplusTime/3600);
    $hourSurplusTime = $daySurplusTime-$hour*3600;
    $minute = floor($hourSurplusTime/60);
    $minuteSurplusTime = $hourSurplusTime-$minute*60;
    $second = $minuteSurplusTime;
    
    $string = '';
    if ($day != 0) {
        $string .= "{$day}天";
    }
    if ($hour != 0) {
        $string .= "{$hour}小时";
    }
    if ($minute != 0) {
        $string .= "{$minute}分";
    }
    if ($second != 0) {
        $string .= "{$second}秒";
    }
    if ($day == 0 && $hour == 0 && $minute == 0 && $second == 0) {
       $string .= '0';
    }
    return $string;
}

/**
 * 获取大小
 *
 * @param integer $size
 * @return string
 */
function sizeToString($size)
{
    $gbSize = $size / (1024*1024*1024);
    $mbSize = $size / (1024*1024);
    $kbSize = $size / (1024);
    if ($gbSize > 1) {
        $string = round($gbSize, 2) . 'GB';
    } else if ($mbSize > 1){
        $string = round($mbSize, 2) . 'MB';
    } else if ($kbSize > 1) {
        $string = round($kbSize, 2) . 'KB';
    } else {
        $string = $kbSize . 'Byte';
    }
    return $string;
}

/**
 * JAVASCRIPT LOCATION
 *
 * @param string $url
 * @param float $time
 * @return string
 */
function jsLocation($url='', $time=0.001)
{
    if (empty($url)) {
        $url = @$_SERVER['HTTP_REFERER'];
    }
    $millisecond = $time*1000;
    $htmlString = "
        <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
        <html xmlns=\"http://www.w3.org/1999/xhtml\">
        <head>
        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
        <title>loading...</title>
        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head>
        
        <body style=\"margin-top:200px;\">
            <script language=\"javascript\">setTimeout(\"location.href='{$url}';\", {$millisecond});</script>
        </body>
        </html>
    ";
    return $htmlString;
}


/**
 * 删除文件夹(删除又有子文件夹和文件)
 *
 * @param string $path
 * @return void
 */
function deleteDirectory($path)
{
    $path = str_replace('\\', '/', $path);
    if (substr($path, -1, 1) != '/') {
        $path .='/';
    }
    if (is_dir($path)) {
        $open = opendir($path);
        if (@rmdir($path)) {//可以删除的话
            closedir($open);
        } else {//如果不能删除
            while ($file = readdir($open)) {
                if ($file != '..' && $file != '.' && is_dir($path . $file)) {
                    deleteDirectory($path . $file . '/');
                } else if ($file != '..' && $file != '.' && !is_dir($path . $file)) {
                    $state = @unlink($path . $file);
                    if (!$state) {
                        exit("File '{$path}' delete error，There may be insufficient permissions, please contact administrator!");
                    }
                }
            }
            closedir($open);
            $state = @rmdir($path);
            if (!$state) {
                exit("Directory '{$path}' delete error，There may be insufficient permissions, please contact administrator!!");
            }
        }
    }
}

/**
 * 新建文件夹
 *
 * @param string $path
 * @param integer $mode
 * @return void
 */
function createDirectory($path, $mode=0777)
{
    $path = str_replace('\\', '/', $path);
    $path = str_replace('//', '/', $path);
    $path = substr($path, strlen($path) - 1, 1) == '/' ? substr($path, 0, strlen($path) - 1) : $path;
    $pathArray = explode('/', $path);

    $isExistsPath = $path;
    $notExistsPath = array();

    for($i = count($pathArray) - 1; $i++; $i > 0) {
        if (is_dir($isExistsPath)) {
            break;
        } else {
            $notExistsPath[] = $isExistsPath;
            //设置下一个路径
            $isExistsPath = substr($isExistsPath, 0, strrpos($isExistsPath, '/'));
        }
    }

    for($i = count($notExistsPath) - 1; $i >= 0; $i--) {
        $state = mkdir($notExistsPath[$i], $mode);
        if (!$state) {
            exit("文件夹“{$notExistsPath[$i]}”创建失败，可能是权限不足，请检查！");
        }
    }
}

/**
 * 移动文件夹
 *
 * @param string $movePath
 * @param string $targetPath
 * @return boolean
 */
function moveFiles($movePath, $targetPath, $childPath = '')
{
    $movePath = str_replace('\\', '/', $movePath);
    if (substr($movePath, -1, 1) != '/') {
        $movePath .='/';
    }
	
    $targetPath = str_replace('\\', '/', $targetPath);
    if (substr($targetPath, -1, 1) != '/') {
        $targetPath .='/';
    }
	
    if (!is_dir($movePath) || !is_dir($targetPath)) {
		return false;
	}

	$open = opendir($movePath . $childPath);
	while ($file = readdir($open)) {
		if ($file != '..' && $file != '.') {
			if ( is_dir($movePath . $childPath . $file)) {//如果是文件夹
				createDirectory($targetPath . $childPath . $file);
				moveFiles($movePath, $targetPath, $childPath . $file . '/');
			} else if (!is_dir($movePath . $childPath . $file)) {//如果是文件
				rename($movePath . $childPath . $file, $targetPath . $childPath . $file);
			}
		}
	}
	closedir($open);
	if (!empty($childPath)) {
		rmdir($movePath . $childPath);
	}
}

/**
 * 重新设置图片大小
 *
 * @param string $sourceFile
 * @param integer $width
 * @param integer $height
 * @return void
 */
function imageResize($sourceFile, $width, $height = 0)
{
	if (!$imageResult = @getimagesize($sourceFile)) {
		return false;
	}

    if ($imageResult['mime'] == 'image/jpeg') {
        $img = @imagecreatefromjpeg($sourceFile);
    } else if ($imageResult['mime'] == 'image/png') {
        $img = @imagecreatefrompng($sourceFile);
    } else if ($imageResult['mime'] == 'image/gif') {
        $img = @imagecreatefromgif($sourceFile);
    }else{
        return ;
    }
    
    $realWidth = $imageResult[0];
    $realHeight = $imageResult[1];
    
    if ($width != 0 && $height == 0) {
        $scale = $width/$realWidth;
    } else if ($width == 0 && $height != 0) {
        $scale = $height/$realHeight;
    } else {
        $scale = min($width/$realWidth, $height/$realHeight);    
    }
    
    if ($scale < 1) {
        $newWidth = floor($scale * $realWidth);
        $newHeight = floor($scale * $realHeight);
        $tempImg = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($tempImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $realWidth, $realHeight);
        imagedestroy($img);
        $img = $tempImg;
    }
    
    if ($imageResult['mime'] == 'image/jpeg') {
        @imagejpeg($img, $sourceFile);
    } else if ($imageResult['mime'] == 'image/png') {
        @imagepng($img, $sourceFile);
    } else if ($imageResult['mime'] == 'image/gif') {
        @imagegif($img, $sourceFile);
    }
}

/**
 * 减切图片
 *
 * @param string $sourceFile
 * @param integer $posX
 * @param integer $posY
 * @param integer $width
 * @param integer $height
 * @param float $sourceZoomScale
 * @return void
 */
function imageCrop($sourceFile, $posX, $posY, $width, $height, $sourceZoomScale)
{
	if (!$imageResult = @getimagesize($sourceFile)) {
		return false;
	}

    if ($imageResult['mime'] == 'image/jpeg') {
        $img = @imagecreatefromjpeg($sourceFile);
    } else if ($imageResult['mime'] == 'image/png') {
        $img = @imagecreatefrompng($sourceFile);
    } else if ($imageResult['mime'] == 'image/gif') {
        $img = @imagecreatefromgif($sourceFile);
    }else{
        return ;
    }
    
    $realWidth = $imageResult[0];
    $realHeight = $imageResult[1];

	$sourceWidth = floor($sourceZoomScale * $realWidth);
	$sourceHeight = floor($sourceZoomScale * $realHeight);
	$tempImg = imagecreatetruecolor($sourceWidth, $sourceHeight);
	imagecopyresampled($tempImg, $img, 0, 0, 0, 0, $sourceWidth, $sourceHeight, $realWidth, $realHeight);
	$realWidth = $sourceWidth;
	$realHeight = $sourceHeight;
	imagedestroy($img);
	$img = $tempImg;

	$tempImg = imagecreatetruecolor($width, $height);
	imagecopyresampled($tempImg, $img, 0, 0, $posX, $posY, $width, $height, $width, $height);
	imagedestroy($img);
	$img = $tempImg;

    if ($imageResult['mime'] == 'image/jpeg') {
        @imagejpeg($img, $sourceFile);
    } else if ($imageResult['mime'] == 'image/png') {
        @imagepng($img, $sourceFile);
    } else if ($imageResult['mime'] == 'image/gif') {
        @imagegif($img, $sourceFile);
    }
}

/**
 * 图片打水印
 *
 * @param string $sourceFile
 * @param string $waterMarkContent
 * @param integer $positionRight
 * @param integer $positionRight
 * @return void
 */
function imageWaterMark($sourceFile, $waterMarkFile, $positionLeft, $positionRight)
{
	if (!$imageResult = @getimagesize($sourceFile)) {
		return false;
	}

    if ($imageResult['mime'] == 'image/jpeg') {
        $img = @imagecreatefromjpeg($sourceFile);
    } else if ($imageResult['mime'] == 'image/png') {
        $img = @imagecreatefrompng($sourceFile);
    } else if ($imageResult['mime'] == 'image/gif') {
        $img = @imagecreatefromgif($sourceFile);
    }else{
        return ;
    }

    $sourceSizeWidth = $imageResult[0];
    $sourceSizeHeight = $imageResult[1];

    $waterMarkExt = substr($waterMarkFile, strrpos($waterMarkFile, '.')+1);//获取文件的类型

	if (!$waterMarImageResult = @getimagesize($sourceFile)) {
		return false;
	}
	
    if ($waterMarImageResult['mime'] == 'image/jpeg') {
        $waterMarkImg = @imagecreatefromjpeg($waterMarkFile);
    } else if ($waterMarImageResult['mime'] == 'image/png') {
        $waterMarkImg = @imagecreatefrompng($waterMarkFile);
    } else if ($waterMarImageResult['mime'] == 'image/gif') {
        $waterMarkImg = @imagecreatefromgif($waterMarkFile);
    }else{
        return ;
    }
    $waterMarkSizeWidth = $waterMarImageResult[0];
    $waterMarkSizeHeight = $waterMarImageResult[1];

    if ($positionLeft < 0) {
        $positionLeft = $sourceSizeWidth + $positionLeft - $waterMarkSizeWidth;
    }
    if ($positionRight < 0) {
        $positionRight = $sourceSizeHeight + $positionRight - $waterMarkSizeHeight;
    }

    imagecopy($sourceImg, $waterMarkImg, $positionLeft, $positionRight, 0, 0, $waterMarkSizeWidth, $waterMarkSizeHeight); 
    if ($imageResult['mime'] == 'image/jpeg') {
        imagejpeg($sourceImg, $sourceFile);  
    } else if ($imageResult['mime'] == 'image/png') {
         imagepng($sourceImg, $sourceFile);  
    } else if ($imageResult['mime'] == 'image/gif') {
        imagegif($sourceImg, $sourceFile);
    }
    imagedestroy($sourceImg);
    imagedestroy($waterMarkImg);
}

/**
 * 获取excel中的时间
 *
 * @param integer $date
 * @return string
 */
function excelTime($date){
    if(is_numeric($date)){
        $jd = GregorianToJD(1, 1, 1970);
        $gregorian = JDToGregorian($jd+intval($date)-25569);
        $date = explode('/',$gregorian);
        $date_str = str_pad($date[2],4,'0', STR_PAD_LEFT)
        ."-".str_pad($date[0],2,'0', STR_PAD_LEFT)
        ."-".str_pad($date[1],2,'0', STR_PAD_LEFT);
        return $date_str;
    }
    return $date;
}

/**
 * 检查页面来源
 *
 * @return void
 */
function checkFrom()
{
    $needCheck = 1;
    if ($needCheck) {
        $from = @$_SERVER['HTTP_REFERER'];
        if (!empty($from)) {
            preg_match("/^(http[s]{0,1}:\/\/)?([^\/]+)/i", "{$from}", $matches);
            $host = $matches[2];
        } else {
            $host = '';
        }
        if ($host != $_SERVER['SERVER_NAME']) {
            exit("{$host} data from is error, please contact administrator!");
        }
    }
}

/**
 * 获取客户端IP地址
 *
 * @return string
 */
function getClientIP()
{
	if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
		$ip = $_SERVER["HTTP_CLIENT_IP"];
	} else if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
		$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	} else if (!empty($_SERVER["REMOTE_ADDR"])) {
		$ip = $_SERVER["REMOTE_ADDR"];
	} else {
		$ip = '';
	}
	return $ip;
}

/**
 * 跳转
 *
 * @param string $url
 * @return string
 */
function redirect($url)
{
    header("location:{$url}");
    exit;
}


/**
 * 调试
 *
 * @param string $array
 * @return string
 */
function dump($array)
{
    echo '<pre>';
    print_r($array);
    echo '</pre>';
}


/**
 * 当用phpexcel或其他excel类把日期从excel中读取出来后，可用下面的函数转成成2009-1-1格式的时间。
 * @param array $ArrayData
 * @return array
 */

function exceltimtetophp($days,$time=false)
{
    if(is_numeric($days))
    {
        $jd = GregorianToJD(1, 1, 1970);
        $gregorian = JDToGregorian($jd+intval($days)-25569);
        $myDate = explode('/',$gregorian);
        $myDateStr = str_pad($myDate[2],4,'0', STR_PAD_LEFT)."-".str_pad($myDate[0],2,'0', STR_PAD_LEFT)."-".str_pad($myDate[1],2,'0', STR_PAD_LEFT).($time ? " 00:00:00" : "");
        return $myDateStr;
    }
    return $time;
}
/**
 * 二位数组排序
 * @param array $ArrayData
 * @return array
 */
function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR")
{
    if(!is_array($ArrayData))
    {
        return $ArrayData;
    }

    // Get args number.
    $ArgCount = func_num_args();

    // Get keys to sort by and put them to SortRule array.
    for($I = 1;$I < $ArgCount;$I ++)
    {
        $Arg = func_get_arg($I);
        if(@!eregi("SORT",$Arg))
        {
            $KeyNameList[] = $Arg;
            $SortRule[]    = '$'.$Arg;
        }
        else
        {
            $SortRule[]    = $Arg;
        }
    }
 
    // Get the values according to the keys and put them to array.
    foreach($ArrayData AS $Key => $Info)
    {
        foreach($KeyNameList AS $KeyName)
        {
            ${$KeyName}[$Key] = $Info[$KeyName];
        }
    }

    // Create the eval string and eval it.
    $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
    eval ($EvalString);
    return $ArrayData;
}

/**
* 将一维数组以多维数组的形式格式化
* @param $arr 待处理的源数据
* @param $parent_id 初始父ID
* @param $f_cat_id 主键名称
* @param $f_parent_id 父节点字段名称
*/

function buildTree($arr = array(), $parent_id = 0, $f_resource_id = 'resource_id', $f_parent_id = 'parent_id'){
	$tree = array();
	foreach ($arr as $k => $v) {
		if($v[$f_parent_id] == $parent_id) {
			$v['childs'] = buildTree($arr, $v[$f_resource_id],$f_resource_id,$f_parent_id);
			if (empty($v['childs'])) {
				unset($v['childs']);
			}
			$tree[] = $v;
		}
	}
	return $tree;
}



/**
* 格式化分类名称，以空白进行缩进
* @param $arr category_array返回结果
* @param $string 缩进空白
* @return array()
*/
function categoryFlatten($arr = array(), $space = '---', $level = 0)
{
	static $flatten = array();
	
	foreach ($arr as $key => $value) {
		$value['level_space'] = str_repeat($space, $level);
		if (isset($value['childs'])) {
			$childs = $value['childs'];
		} else {
			$childs = array();
		}
		unset($value['childs']);
		$flatten[] = $value;
		categoryFlatten($childs, $space, $level + 1);
	}
	return $flatten;
}



/**
 * 计算页数和当前页
 * @param array $filter
 * @return array
 */
function page_and_size($filter)
{
	$filter['page_size'] = (isset($filter['page_size']) && intval($filter['page_size']) > 0) ? (int) $filter['page_size'] : 20;
	$filter['page_count'] = max(ceil($filter['record_count'] / $filter['page_size']), 1);
	$filter['page'] = (isset($filter['page']) && intval($filter['page']) > 0) ? (int) $filter['page'] : 1;
	if ($filter['page'] > $filter['page_count']) $filter['page'] = $filter['page_count'];
	$filter['sort_flag'] = ($filter['sort_order'] == "DESC") ? 'sorting_desc' : 'sorting_asc';
	return $filter;
}

/**
 * 取得分页参数
 * @param array $filter
 * @return array
 */
function get_pager_param($filter)
{
	$request = new Zend_Controller_Request_Http();
	$filter['page'] = $request->getPost('page') ? intval($request->getPost('page')) : 1;
	$filter['page_size'] = $request->getPost('page_size') ? intval($request->getPost('page_size')) : 20;
	$filter['sort_by'] = $request->getPost('sort_by') ? intval($request->getPost('sort_by')) : '';
	$filter['sort_order'] = $request->getPost('sort_order') ? intval($request->getPost('sort_order')) : 'asc';
	return $filter;
}

/**
 * 递归取得父resourceid
 * @param 
 * @return array
 */
function parentids($arr,$parent_id,$i){
	static $parentarr = array();
	foreach ($arr as $k => $v) {
		if ($parent_id == $v['resource_id']) {
			$parentarr[$i][] = $v['resource_id'];
			parentids($arr,$v['parent_id'],$i);
		}
	}
	if (isset($parentarr[$i-1])) {
		unset($parentarr[$i-1]);
	}
	return $parentarr;
}
/**
 * 递归取得子resourceid
 * @param 
 * @return array
 */
function childids($arr,$resource_id,$i){
	static $childarr = array();
	foreach ($arr as $k => $v) {
		if ($resource_id == $v['parent_id']) {
			$childarr[$i][] = $v['resource_id'];
			childids($arr,$v['resource_id'],$i);
		}
	}
	if (isset($childarr[$i-1])) {
		unset($childarr[$i-1]);
	}
	return $childarr;
}